const { createApp, ref, computed, onMounted } = Vue;
createApp({
    setup() {
        const today = new Date();
        const currentDate = ref(new Date());
        const signedDates = ref([]);
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        const ACCESSTOKEN = ref("");
        const miniprogram = ref(false);
        const loading = ref(false);
        const formData = ref({});
        onMounted(() => {
            function ready() { //判断是否在web-view页
                miniprogram.value = window.__wxjs_environment === 'miniprogram'
            }
            if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
                document.addEventListener('WeixinJSBridgeReady', ready, false)
            } else {
                ready()
            }
            let URL = window.location.href;
            ACCESSTOKEN.value = getQueryObject(URL, 'ACCESSTOKEN');

            getData()
        });

        // 当前年月
        const currentYear = computed(() => currentDate.value.getFullYear());
        const currentMonth = computed(() => currentDate.value.getMonth());

        // 月份天数
        const daysInMonth = computed(() => {
            return new Date(currentYear.value, currentMonth.value + 1, 0).getDate();
        });

        // 月份第一天是星期几
        const firstDayOfMonth = computed(() => {
            return new Date(currentYear.value, currentMonth.value, 1).getDay();
        });

        // 日历天数数组（包括前面空白和当月天数）
        const days = computed(() => {
            const daysArray = [];

            // 添加空白
            for (let i = 0; i < firstDayOfMonth.value; i++) {
                daysArray.push(0);
            }

            // 添加当月天数
            for (let i = 1; i <= daysInMonth.value; i++) {
                daysArray.push(i);
            }

            return daysArray;
        });

        // 已签到的天数
        const signedDays = computed(() => {
            return signedDates.value.filter(date => {
                const d = new Date(date);
                return d.getFullYear() === currentYear.value &&
                    d.getMonth() === currentMonth.value;
            }).length;
        });

        // 连续签到天数
        const continuousDays = computed(() => {
            if (signedDates.value.length === 0) return 0;

            const sortedDates = [...signedDates.value].sort().reverse();
            let continuous = 0;
            let prevDate = null;

            for (let i = 0; i < sortedDates.length; i++) {
                const currentDate = new Date(sortedDates[i]);
                if (prevDate === null) {
                    continuous = 1;
                    prevDate = currentDate;
                    continue;
                }

                // 检查是否是连续日期
                const diffTime = prevDate - currentDate;
                const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

                if (diffDays === 1) {
                    continuous++;
                    prevDate = currentDate;
                } else {
                    break;
                }
            }

            return continuous;
        });

        // 今天是否已签到
        const isTodaySigned = computed(() => {
            const todayStr = getYMDDate(today);
            return signedDates.value.includes(todayStr);
        });

        // 查询每次签到获取的积分数
        const getData = () => {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'sign_in_config',
                    Condition: `Row_Status = '0' ORDER BY sign_in_config.Create_Datetime DESC LIMIT 1`,
                },
                success: (res) => {
                    if (res.length == 1) {
                        formData.value = res[0];
                    }
                },
                complete: (XMLHttpRequest) => {
                    if (XMLHttpRequest.status == 302) {
                        wx.miniProgram.navigateTo({
                            url: miniProgram,
                        })
                    }
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(`/micro/smart/mohe/resident/getSignInformation?yearMonth=${getYMDate(currentDate.value)}&phone=`)}`,
                method: "GET",
                success: (res) => {
                    if (res.code == 200) {
                        const { data } = res.data;
                        signedDates.value = data;
                    }
                },
                complete: (XMLHttpRequest) => {
                    if (XMLHttpRequest.status == 302) {
                        wx.miniProgram.navigateTo({
                            url: miniProgram,
                        })
                    }
                },
                dataType: "json"
            });
        }

        // 判断是否是当前日期
        const isCurrentDay = (day) => {
            return currentYear.value === today.getFullYear() &&
                currentMonth.value === today.getMonth() &&
                day === today.getDate();
        };

        // 判断某天是否已签到
        const isSigned = (day) => {
            if (day === 0) return false;

            const dateStr = getYMDDate(new Date(currentYear.value, currentMonth.value, day));
            return signedDates.value.includes(dateStr);
        };

        // 今天签到
        const signToday = () => {
            if (isTodaySigned.value) return;
            loading.value = true;
            const { Points } = formData.value;

            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/population/getPersonalPoint`,
                method: "GET",
                success: (personal_points_account) => {
                    let lJSONObject_DataSet = new Object();
                    let sign_in_log = [{
                        Sign_In_Date: getYMDDate(today),
                        Points
                    }]
                    let personal_points_change_log = {
                        ID_Card_Number: '',
                        Points_Title: '签到获取积分',
                        Points_Type: '0',
                        Change_Points: Points,
                        Notes: '签到获取积分',
                    }
                    if (personal_points_account.length == 1) {//有账户
                        const Total_Points = accAdd(personal_points_account[0].Total_Points, Points);
                        const Remain_Points = accAdd(personal_points_account[0].Remain_Points, Points);
                        personal_points_account[0].Total_Points = Total_Points;
                        personal_points_account[0].Remain_Points = Remain_Points;
                        lJSONObject_DataSet = {
                            Add: {
                                sign_in_log,
                                personal_points_change_log: [{
                                    ...personal_points_change_log,
                                    Remain_Points,
                                }],
                            },
                            Modify: {
                                personal_points_account,
                            }
                        }
                    } else {//无账户
                        lJSONObject_DataSet = {
                            Add: {
                                sign_in_log,
                                personal_points_change_log: [{
                                    ...personal_points_change_log,
                                    Remain_Points: Points
                                }],
                                personal_points_account: [{
                                    ID_Card_Number: '',
                                    Points_Type: '0',
                                    Total_Points: Points,
                                    Remain_Points: Points,
                                    Sales_Points: '0'
                                }]
                            },
                        }
                    }

                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            const todayStr = getYMDDate(today);
                            signedDates.value.push(todayStr);
                        }
                        loading.value = false;
                    })
                },
                complete: (XMLHttpRequest) => {
                    if (XMLHttpRequest.status == 302) {
                        wx.miniProgram.navigateTo({
                            url: miniProgram,
                        })
                    }
                },
                dataType: "json"
            });
        };

        const submitSave = (Data, response) => {
            const websocket = new WebSocketClient();
            websocket.init({
                url: ws + '/generalSave/' + getCookie('token'),
                onopen: () => {
                    let lJSONObject_DataSet = {
                        Data, AccessToken: getCookie('token'),
                        replaceParameter: "ID_Card_Number",
                    }
                    websocket.send(JSON.stringify(lJSONObject_DataSet));
                },
                onmessage: (data) => {
                    try {
                        const res = JSON.parse(data);
                        websocket.close();
                        if (res.REDIRECT && res.REDIRECT == 'REDIRECT') {//重定向
                            wx.miniProgram.navigateTo({
                                url: miniProgram,
                            })
                        } else {
                            response ? response(res) : null;
                        }
                    } catch (error) { }
                },
            })
        };

        // 上个月
        const prevMonth = () => {
            currentDate.value = new Date(currentYear.value, currentMonth.value - 1, 1);
            getData();
        };

        // 下个月
        const nextMonth = () => {
            currentDate.value = new Date(currentYear.value, currentMonth.value + 1, 1);
            getData();
        };

        return {
            formData,
            currentDate,
            currentYear,
            currentMonth,
            days,
            weekdays,
            signedDates,
            signedDays,
            continuousDays,
            isTodaySigned,
            daysInMonth,
            isCurrentDay,
            isSigned,
            signToday,
            getData,
            prevMonth,
            nextMonth
        };
    }
}).mount('#app');